<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="108px"
    >
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获赠人姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获赠人电话" prop="recipientPhone">
        <el-input
          v-model="queryParams.recipientPhone"
          placeholder="请输入发放人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:couponList:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >

    <el-table-column label="适用区域" align="center" prop="zyCoupon.regionName" :show-overflow-tooltip="true" width="120">
      </el-table-column>
      <el-table-column label="适用门店" :show-overflow-tooltip="true" align="center" prop="zyCoupon.storeName">
      </el-table-column>
      <el-table-column label="优惠券名称" align="center" prop="zyCoupon.name" width="120" />
      <el-table-column label="优惠券类型" align="center" prop="zyCoupon.discountsType" width="120">

        <template slot-scope="scope">
          <span>{{ scope.row.zyCoupon.discountsType == 1 ? '折扣券' : '立减券' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="优惠门槛" align="center" prop="zyCoupon.fullAmount" width="120" />
      <el-table-column label="优惠金额" align="center" prop="discountAmount" width="120">
        <template slot-scope="scope">
          <span>{{
            scope.row.zyCoupon.discountAmount ? scope.row.zyCoupon.discountAmount : "暂无"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="折扣率" align="center" prop="zyCoupon.discountRate" width="120" />

      <el-table-column label="适用项目" :show-overflow-tooltip="true" align="center" prop="zyCoupon.projectName">
      </el-table-column>


      <!-- <el-table-column label="优惠券名字" align="center" prop="couponName" /> -->
      <el-table-column label="赠送数量" align="center" prop="giveNumber" />

      <el-table-column label="获赠人" align="center" prop="nickName" />

      <el-table-column label="获赠人手机号" align="center" prop="phoneNumber" />
      

      <el-table-column label="获赠说明" align="center" prop="giveExplain" />

      <!-- <el-table-column label="操作人" align="center" prop="createBy" /> -->

      <el-table-column label="获赠时间" align="center" prop="createTime" />
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listcoupon,
  giveList,
  listMemberRegion,
} from "@/api/system/coupon/couponList";

export default {
  name: "Store",
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      getPath: [],
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponName: null,
        nickName: null,
        createBy: null,
      },
      // 表单参数
      form: {
        discountsType: 1,
        couponTypeValue: 3,
        useTimeType: 1,
        overLayUseType: [],
        useLimit: [],
        useLimits: 1,
        userTime: 1,
        state: "1",
        ableUseStartTime: null,
        ableUseEndTime: null,
      },
      options: [],
      List: [
        {
          key: "1",
          value: "上架",
        },
        {
          key: "0",
          value: "下架",
        },
      ],
      region: [],
      store: [],
      time: [],
      week: [
        {
          key: "周一",
          value: "周一",
        },
        {
          key: "周二",
          value: "周二",
        },
        {
          key: "周三",
          value: "周三",
        },
        {
          key: "周四",
          value: "周四",
        },
        {
          key: "周五",
          value: "周五",
        },
        {
          key: "周六",
          value: "周六",
        },
        {
          key: "周日",
          value: "周日",
        },
      ],
      Day: [
        { key: "1", value: "1号" },
        { key: "2", value: "2号" },
        { key: "3", value: "3号" },
        { key: "4", value: "4号" },
        { key: "5", value: "5号" },
        { key: "6", value: "6号" },
        { key: "7", value: "7号" },
        { key: "8", value: "8号" },
        { key: "9", value: "9号" },
        { key: "10", value: "10号" },
        { key: "11", value: "11号" },
        { key: "12", value: "12号" },
        { key: "13", value: "13号" },
        { key: "14", value: "14号" },
        { key: "15", value: "15号" },
        { key: "16", value: "16号" },
        { key: "17", value: "17号" },
        { key: "18", value: "18号" },
        { key: "19", value: "19号" },
        { key: "20", value: "20号" },
        { key: "21", value: "21号" },
        { key: "22", value: "22号" },
        { key: "23", value: "23号" },
        { key: "24", value: "24号" },
        { key: "25", value: "25号" },
        { key: "26", value: "26号" },
        { key: "27", value: "27号" },
        { key: "28", value: "28号" },
        { key: "29", value: "29号" },
        { key: "30", value: "30号" },
        { key: "31", value: "31号" },
      ],
      type: [],
      project: [],
      checked: false,
      checked1: false,
      checked2: false,
      checked3: false,
      isNotEditor: "y",
    };
  },
  watch: {
    // "form.regionIds"(newVal, oldVal) {
    //   if (newVal.length > 0) {
    //     const regionIds = newVal.join(",");
    //     console.log(regionIds,'regionIds')
    //     this.$nextTick(() => {
    //       listMemberStore({ regionIds }).then((res) => {
    //         this.store = res.data.map((rItem) => {
    //           return {
    //             key: rItem.id,
    //             value: rItem.storeName,
    //           };
    //         });
    //       });
    //     });
    //   }
    // },
    "form.regionIds": {
      handler: function (newVal) {
        if (newVal.length > 0) {
          const regionIds = newVal.join(",");
          this.$nextTick(() => {
            listMemberStore({ regionIds }).then((res) => {
              this.store = res.data.map((rItem) => {
                return {
                  key: rItem.id,
                  value: rItem.storeName,
                };
              });
            });
          });
        }
      },
    },
    "form.storeIds": {
      handler: function (newVal) {
        if (newVal.length > 0) {
          const storeIds = newVal.join(",");
          this.$nextTick(() => {
            listitem({ storeIds }).then((res) => {
              this.project = res.data.map((rItem) => {
                return {
                  key: rItem.id,
                  value: rItem.itemName,
                };
              });
            });
          });
        }
      },
    },
  },
  created() {
    this.getList();
    // this.listregion();
    // this.listslot();
    // this.listtype();
  },
  methods: {
    //使用日期全选change事件
    checkDay(e) {
      let resValues = this.Day.map((item) => item.key);
      console.log(resValues, "9090909090900");
      // 如果checkbox为false，则为反选，选择数组为空
      if (!e.target.checked) {
        this.form.useDay = [];
      } else {
        // 如果checkbox为true，则为全选，选择数组添加所有数据
        let res = [...resValues];
        this.form.useDay = res;
      }
    },
    //区域全选change事件
    checkChange(e) {
      let resValues = this.region.map((item) => item.key);
      // 如果checkbox为false，则为反选，选择数组为空
      if (!e.target.checked) {
        this.form.regionIds = [];
      } else {
        // 如果checkbox为true，则为全选，选择数组添加所有数据
        let res = [...resValues];
        this.form.regionIds = res;
      }
    },
    //门店全选change事件
    checkStoreChange(e) {
      let resValues = this.store.map((item) => item.key);
      // 如果checkbox为false，则为反选，选择数组为空
      // 如果checkbox为true，则为全选，选择数组添加所有数据

      if (e.target.checked == false) {
        this.form.storeIds = [];
      } else {
        // 如果checkbox为true，则为全选，选择数组添加所有数据
        let res = [...resValues];
        this.form.storeIds = res;
      }
    },
    //项目全选change事件
    checkProjectChange(e) {
      let resValues = this.project.map((item) => item.key);
      // 如果checkbox为false，则为反选，选择数组为空
      if (!e.target.checked) {
        this.form.projectId = [];
      } else {
        // 如果checkbox为true，则为全选，选择数组添加所有数据
        let res = [...resValues];
        this.form.projectId = res;
      }
    },
    getDateWeek() {
      const now = new Date();
      const nowTime = now.getTime();
      const day = now.getDay();
      const oneDayTime = 24 * 60 * 60 * 1000;
      const mondayTime = nowTime - (day - 2) * oneDayTime; //默认是周二
      this.weeklyDate = new Date(mondayTime);
      this.newDateWeekHandle();
    },
    newDateWeekHandle() {
      const now = new Date(this.weeklyDate);
      const nowTime = now.getTime();
      const day = now.getDay();
      const oneDayTime = 24 * 60 * 60 * 1000;
      const mondayTime = nowTime - (day - 1) * oneDayTime;
      const sundayTime = nowTime + (7 - day) * oneDayTime;
      this.startDate = this.$moment(mondayTime).format("YYYY-MM-DD");
      this.endDate = this.$moment(sundayTime).format("YYYY-MM-DD");
    },
    listtype() {
      listtype().then((res) => {
        this.type = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.typeName,
          };
        });
      });
    },
    listslot() {
      listslot().then((res) => {
        // console.log(res,888);
        this.time = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.useSlot,
          };
        });
      });
    },
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      // const selectedOption = this.region.find((item) => item.key === value);
      // console.log(selectedOption,'selectedOption666')
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.regionName = selectedValue;
      const resValues = this.region.map((item) => item.key);
      if (value.length === resValues.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
      this.form.regionIds = value;
      if (value) {
        this.form.storeIds = "";
      }
    },
    //门店change事件
    changeStore(value) {
      // const selectedOption = this.store.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.storeName = selectedValue;
      // listitem({ storeId: value }).then((res) => {
      //   this.project = res.rows.map((rItem) => {
      //     return {
      //       key: rItem.id,
      //       value: rItem.itemName,
      //     };
      //   });
      //   console.log(this.project, 999);
      // });
      const resValues = this.store.map((item) => item.key);
      if (value.length === resValues.length) {
        this.checked1 = true;
      } else {
        this.checked1 = false;
      }
      this.form.storeIds = value;
      if (value) {
        this.form.projectId = "";
      }
    },
    //项目change事件
    changeProject(value) {
      const resValues = this.project.map((item) => item.key);
      if (value.length === resValues.length) {
        this.checked2 = true;
      } else {
        this.checked2 = false;
      }
      this.form.projectId = value;
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      giveList(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        storeIds: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        discountsType: 1,
        couponTypeValue: 3,
        discountRate: null,
        fullAmountRate: null,
        fullAmount: null,
        fullAmount1: null,
        fullAmount2: null,
        discountAmount: null,
        oneGiveCount: null,
        totalUseCount: null,
        intervalCount: 1,
        effectiveDays: null,
        useToday: null,
        useDay: null,
        useTimeType: 1,
        overLayUseType: [],
        useLimit: [],
        userTime: 1,
        state: "1",
        ableUseStartTime: null,
        ableUseEndTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
      this.isNotEditor = "y";
    },
    // 上下架
    handleGround(row, state) {
      const params = {
        id: row.id,
        state: state,
      };
      this.$confirm(
        `此操作将${state === 1 ? "上架" : "下架"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updatecouponsssss(params).then((res) => {
            this.$message({
              type: "success",
              message: `${state === 1 ? "上架" : "下架"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上下架",
          });
        });
    },
    //切换
    handleChange(val) {
      if (val === 1) {
        this.form.fullAmount2 = "";
        this.form.discountAmount = "";
        if (this.form) {
          this.form.fullAmount1 = this.form.fullAmount;
          this.form.discountRate = this.form.discountRate;
          this.form.fullAmountRate = this.form.fullAmountRate;
        }
      } else {
        this.form.fullAmount1 = "";
        this.form.discountRate = "";
        this.form.fullAmountRate = "";
      }
      this.$refs.form.clearValidate();
    },
    //使用时间类型change事件
    timeTypeChange(val) {
      if (val === 1) {
        this.form.userTime = "";
        this.form.useToday = "";
        this.form.useDay = "";
        this.form.ableUseStartTime = "";
        this.form.ableUseEndTime = "";
      }
    },
    //选择周期或者日期change事件
    userTimeChange(val) {
      console.log(val, "7878787878");
      if (val === 1) {
        this.form.useDay = "";
        this.form.ableUseStartTime = "";
        this.form.ableUseEndTime = "";
      } else {
        this.form.useToday = "";
        this.form.ableUseStartTime = "";
        this.form.ableUseEndTime = "";
      }
    },
    //优惠券类型change事件
    couponChange(val) {
      // if(val === 1){
      //   this.form.regionIds = ''
      //   this.form.storeIds = ''
      //   this.form.projectId = ''
      // }
    },
    /** 修改按钮操作 */
    handleUpdate(row, flag = "y") {
      this.reset();
      const id = row.id || this.ids;
      this.isNotEditor = flag;
      getcoupon(id).then((response) => {
        this.form = response.data;
        if (response.data.regionIds == "") {
          response.data.regionIds = null;
        } else {
          response.data.regionIds = response.data.regionIds
            .split(",")
            .map(Number);
        }
        if (response.data.storeIds == "") {
          response.data.storeIds = null;
        } else {
          response.data.storeIds = response.data.storeIds
            .split(",")
            .map(Number);
        }
        if (response.data.projectId == "") {
          response.data.projectId = null;
        } else {
          response.data.projectId = response.data.projectId
            .split(",")
            .map(Number);
        }
        if (response.data.useTimeType === 1) {
          this.form.useToDay = "";
        } else {
          this.form.useDay = "";
        }
        this.form.discountsType === 1
          ? (this.form.fullAmount1 = response.data.fullAmount)
          : (this.form.fullAmount2 = response.data.fullAmount);
        response.data.useToday = response.data.useToday
          ? response.data.useToday.split(",")
          : "";
        response.data.useDay = response.data.useDay
          ? response.data.useDay.split(",")
          : "";
        response.data.overLayUseType = response.data.overLayUseType
          ? response.data.overLayUseType.split(",")
          : "";
        response.data.useLimit = response.data.useLimit
          ? response.data.useLimit.split(",")
          : "";
        response.data.couponTypeValue = Number(response.data.couponTypeValue);
        response.data.couponTypeName = "";
        this.open = true;
        this.title = "修改门店";
        // listitem({ storeId: response.data.storeId }).then((res) => {
        //   console.log(res, 123);
        //   this.project = res.rows.map((rItem) => {
        //     return {
        //       key: rItem.id,
        //       value: rItem.itemName,
        //     };
        //   });
        // });
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            // this.form.useToday =  this.form.useToday.join(",");
            this.form.useToday = this.form.useToday
              ? this.form.useToday.join(",")
              : null;
            this.form.getPath = this.getPath ? this.getPath.join(",") : null;
            this.form.useDay = this.form.useDay
              ? this.form.useDay.join(",")
              : null;
            this.form.overLayUseType = this.form.overLayUseType
              ? this.form.overLayUseType.join(",")
              : null;
            this.form.useLimit = this.form.useLimit
              ? this.form.useLimit.join(",")
              : null;
            this.form.fullAmount =
              this.form.discountsType === 1
                ? this.form.fullAmount1
                : this.form.fullAmount2;
            // this.form.regionIds = this.form.regionIds ? this.form.regionIds.join(",") : null
            // this.form.storeIds = this.form.storeIds ? this.form.storeIds.join(",") : null
            // this.form.projectId = this.form.projectId ? this.form.projectId.join(",") : null
            // this.form.couponTypeId = 25
            if (this.form.regionIds) {
              this.form.regionIds = this.form.regionIds.join(",");
            }
            if (this.form.storeIds) {
              this.form.storeIds = this.form.storeIds.join(",");
            }
            if (this.form.projectId) {
              this.form.projectId = this.form.projectId.join(",");
            }
            updatecoupon(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.getPath = this.getPath ? this.getPath.join(",") : null;

            this.form.useToday = this.form.useToday
              ? this.form.useToday.join(",")
              : null;
            this.form.useDay = this.form.useDay
              ? this.form.useDay.join(",")
              : null;
            this.form.overLayUseType = this.form.overLayUseType
              ? this.form.overLayUseType.join(",")
              : null;
            this.form.useLimit = this.form.useLimit
              ? this.form.useLimit.join(",")
              : null;
            this.form.regionIds = this.form.regionIds
              ? this.form.regionIds.join(",")
              : null;
            this.form.storeIds = this.form.storeIds
              ? this.form.storeIds.join(",")
              : null;
            this.form.projectId = this.form.projectId
              ? this.form.projectId.join(",")
              : null;
            this.form.fullAmount =
              this.form.discountsType === 1
                ? this.form.fullAmount1
                : this.form.fullAmount2;
            // this.form.couponTypeId = 25
            // if (this.form.projectId) {
            //   this.form.projectId = this.form.projectId.join(",");
            // }
            console.log(this.form, "8989898989");
            addcoupon(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认重置编号为"' + ids + '"的数据项？')
        .then(function () {
          return listResetPwd({ userId: ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("重置成功");
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return delitecoupon(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
.checkboxWrapper {
  padding: 8px 20px;
  border-bottom: 1px solid #ccc;
}

.descStyle {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tooltip {
  max-width: 650px;
}
</style>
